#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import cexapi
import datetime
import time
import re

import krakenex

showTrue=1
showFalse=0

kraConn = krakenex.API()
kraConn.load_key('kraken.key')

def calcSellBuyMargin(tickerKra):
    return 100*(tickerKra['Sells']/tickerKra['Buys']-1)

def balanceKRA(show):
    KRA_balance = kraConn.query_private('Balance')
    #ktoEUR = KRA_balance['result']['ZEUR']
    ktoBTC = KRA_balance['result']['XXBT']
    ktoLTC = KRA_balance['result']['XLTC']
    if show:
        print "KraKto: BTC=",ktoBTC, "LTC=",ktoLTC        
    return {u'BTC':float(ktoBTC),u'LTC':float(ktoLTC)}
    
def getKraTicker(show):
    kraBitcoin2ltc = kraConn.query_public('Ticker', {'pair':'XXBTXLTC'})
    bestSell=float(kraBitcoin2ltc['result']['XXBTXLTC']['a'][0])
    bestBuy=float(kraBitcoin2ltc['result']['XXBTXLTC']['b'][0])
    retVal={u'Sells':bestSell,u'Buys':bestBuy}
    if show:
        print "KRA sells 1 BTC for",bestSell, "LTC"
        print "KRA buys  1 BTC for",bestBuy, "LTC"
        print "sellBuyMargin=",round(calcSellBuyMargin(retVal),2),"%"
    return retVal

def getKraOpenOrders(show):
    openOrdersCount=0    
    try:
        openOrders = kraConn.query_private('OpenOrders', {'pair':'XXBTXLTC'})
        #print openOrders
        for key in openOrders['result']['open'].keys():                
                type =openOrders['result']['open'][key]['descr']['type']
                price=openOrders['result']['open'][key]['descr']['price']
                volBTC=openOrders['result']['open'][key]['vol']
                order=openOrders['result']['open'][key]['descr']['order']
                openOrdersCount=openOrdersCount+1
                if show:
                    print type, price, volBTC, order
    except:
        print "no open Orders"
    return [openOrdersCount,openOrders]        


     

 


counter=100
while True and counter>0:
    #counter=counter-1
    try:
        print "\nStatus"  
        balKra=balanceKRA(showTrue)
        print "BTC=",float(balKra['BTC'])
        if balKra['BTC']<0.02:
            kraConn.query_private('AddOrder', {'pair': 'XXBTXLTC',
                                     'type': 'buy',
                                     'ordertype': 'market',                                     
                                     'volume': '0.04'                            
                                     })
        if balKra['LTC']<0.5:
            kraConn.query_private('AddOrder', {'pair': 'XXBTXLTC',
                                     'type': 'sell',
                                     'ordertype': 'market',                                     
                                     'volume': '0.04'                            
                                     })
        
        tickerKra=getKraTicker(showTrue)
        diff=tickerKra['Sells']-tickerKra['Buys']
        increment=diff/20
        
        openKraOrders=getKraOpenOrders(showFalse)    
        if openKraOrders[0]:  
            sellFound=0
            buyFound=0
            print "OPEN ORDERS"       
            for key in openKraOrders[1]['result']['open'].keys():                
                type =openKraOrders[1]['result']['open'][key]['descr']['type']
                price=float(openKraOrders[1]['result']['open'][key]['descr']['price'])
                volBTC=openKraOrders[1]['result']['open'][key]['vol']
                order=openKraOrders[1]['result']['open'][key]['descr']['order']
                print type, price, volBTC, order
                if type=='sell':                    
                    sellFound=1
                    if price>tickerKra['Sells'] and calcSellBuyMargin(tickerKra)>=1:
                        print "Adapt Sell Order"
                        print "ticker=",tickerKra['Sells']
                        print "myPrice=",price
                        kraConn.query_private('CancelOrder', {'txid':key})
                        kraConn.query_private('AddOrder', {'pair': 'XXBTXLTC',
                                     'type': 'sell',
                                     'ordertype': 'limit',
                                     'price': tickerKra['Sells']-increment,
                                     'volume': '0.01'                            
                                     })
                if type=='buy':                    
                    buyFound=1
                    if price<tickerKra['Buys'] and calcSellBuyMargin(tickerKra)>=1:
                        print "Adapt Buy Order"
                        kraConn.query_private('CancelOrder', {'txid':key})
                        kraConn.query_private('AddOrder', {'pair': 'XXBTXLTC',
                                'type': 'buy',
                                 'ordertype': 'limit',
                                 'price': tickerKra['Buys']+increment,
                                'volume': '0.01'
                                 })
            if not sellFound:
                print "put new sell Order"
                kraConn.query_private('AddOrder', {'pair': 'XXBTXLTC',
                                     'type': 'sell',
                                     'ordertype': 'limit',
                                     'price': tickerKra['Sells']-increment,
                                     'volume': '0.01'                            
                                     })
            if not buyFound:
                print "put new buy Order"
                kraConn.query_private('AddOrder', {'pair': 'XXBTXLTC',
                                'type': 'buy',
                                 'ordertype': 'limit',
                                 'price': tickerKra['Buys']+increment,
                                'volume': '0.01'
                                 })            
                            
        else:
            print "no open KraOrders, Create some..."      
            print "put sell @",tickerKra['Sells']-increment      
            kraConn.query_private('AddOrder', {'pair': 'XXBTXLTC',
                                     'type': 'sell',
                                     'ordertype': 'limit',
                                     'price': tickerKra['Sells']-increment,
                                     'volume': '0.01'                            
                                     })
            print "put buy @",tickerKra['Buys']+increment      
            kraConn.query_private('AddOrder', {'pair': 'XXBTXLTC',
                                'type': 'buy',
                                 'ordertype': 'limit',
                                 'price': tickerKra['Buys']+increment,
                                'volume': '0.01'
                                 })
       
               
   
   
   
    
        time.sleep(10)
    except:
        print "general Exception"
        time.sleep(60)
        